package com.blueheart.music.service.impl;

import com.blueheart.music.exception.BaseException;
import com.blueheart.music.exception.BaseExceptionEnum;
import com.blueheart.music.mapper.ConsumerMapper;
import com.blueheart.music.model.pojo.Consumer;
import com.blueheart.music.service.ConsumerService;
import com.blueheart.music.util.MD5Util;
import com.qcloud.cos.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ConsumerServiceImpl implements ConsumerService {
    @Autowired
    private ConsumerMapper consumerMapper;
    /**
     * 增加用户
     *
     * @param consumer
     * @return
     */
    @Override
    public Boolean addConsumer(Consumer consumer) {
        Consumer consumer1 = consumerMapper.selectByUserName(consumer.getUsername());
        if (consumer1==null){
            return consumerMapper.insertSelective(consumer)>0;
        }
        throw new BaseException(BaseExceptionEnum.USER_EXIST);
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Boolean removeConsumer(Integer id) {
        return consumerMapper.deleteByPrimaryKey(id)>0;
    }

    /**
     * 更新用户
     *
     * @param consumer
     * @return
     */
    @Override
    public Boolean reviseConsumer(Consumer consumer) {
        return consumerMapper.updateByPrimaryKeySelective(consumer)>0;
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<Consumer> findAll() {
        return consumerMapper.seleteAll();
    }

    /**
     * 通过id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public Consumer findById(Integer id) {
        return consumerMapper.selectByPrimaryKey(id);
    }

    /**
     * 通过名字查询用户
     *
     * @param username
     * @return
     */
    @Override
    public Consumer findByUserName(String username) {
        return consumerMapper.selectByUserName(username);
    }

    /**
     * 用户登录
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    public Consumer login(String userName, String password) {
        String md5 = MD5Util.getMD5(password);
        Consumer consumer = consumerMapper.selectByConsumer(userName, md5);
        if (consumer != null) {
            return consumer;
        }
        throw  new BaseException(BaseExceptionEnum.LOGIN_ERROR);
    }
}
